package com.etop.service;

import com.etop.beans.Activity;
import com.etop.beans.Borrow;
import com.etop.beans.Goods;
import com.etop.beans.ProFile;
import com.etop.beans.Pro_schedule;
import com.etop.beans.Project;
import com.etop.beans.User;
import com.etop.beans.User_project;
import com.etop.dao.GoodsDao;
import com.etop.dao.ManagerDao;
import com.etop.dto.UserGoodsDTO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

public class ManagerService {

    private ManagerDao managerDao;
    private GoodsDao goodsDao;

    public ManagerDao getManagerDao() {
        return managerDao;
    }

    public void setManagerDao(ManagerDao managerDao) {
        this.managerDao = managerDao;
    }

    public GoodsDao getGoodsDao() {
        return goodsDao;
    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    /**
     * 将project的所有内容存到list中
     *
     * @return
     */
    public List<Project> listOfProject() {
        return managerDao.listOfProject();
    }

    /**
     * 将pro_schedule的所有内容存入list中
     *
     * @return
     */
    public List<Pro_schedule> listOfProSchedule() {
        return managerDao.listOfProSchedule();
    }

    /**
     * 将user_project的所有内容存入list中
     *
     * @return
     */
    public List<User_project> listOfUserProject() {
        return managerDao.listOfUserProject();
    }

    /**
     * 将一个项目的负责人导入到list
     *
     * @param pro
     * @return
     */
    public List<String> listLeadersOfOneProject(Project pro) {
        return managerDao.listLeadersOfOneProject(pro);
    }

    /**
     * 将一个项目的负责人导入到list
     *
     * @param pro
     * @return
     */
    public List<String> listMembersOfOneProject(Project pro) {
        return managerDao.listMembersOfOneProject(pro);
    }

    /**
     * 返回特定项目的项目进度报告表
     *
     * @param list
     * @param pro
     * @return
     */
    public List<Pro_schedule> listSchedulesOfOneProject(List<Pro_schedule> list, Project pro) {
        if (list == null) {
            return null;
        }
        List<Pro_schedule> list2 = new ArrayList<Pro_schedule>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getP_id() == pro.getId()) {
                list2.add(list.get(i));
            }
        }
        return list2;
    }

    /**
     * 删除项目编号为id的项目
     *
     * @param id
     */
    public void deleteOneProject(int id) {
        this.managerDao.deleteOneProject(id);
    }

    /**
     * 处理下载文件（PS：在找有没有简单的方法下载）
     *
     * @param proFileId
     * @param response
     */
    public void downLoadFile(int proFileId, HttpServletResponse response) {
        ProFile proFile = managerDao.loadProFileById(proFileId);
        System.out.println("proId" + proFile.getFile());
        //读取要下载的文件，保存到文件输入流
        FileInputStream in = null;
        //创建输出流
        OutputStream out = null;
        try {
//            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(proFile.getName(), "UTF-8"));

            response.setHeader("content-disposition", "attachment;filename=" + new String(proFile.getName().getBytes("gb2312"), "ISO8859-1"));
            System.out.println("getPath" + URLEncoder.encode(proFile.getName(), "UTF-8"));
            in = new FileInputStream(proFile.getFile());
            out = response.getOutputStream();
            //创建缓冲区
            byte buffer[] = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区当中
            while ((len = in.read(buffer)) > 0) {
                //输出缓冲区的内容到浏览器，实现文件下载
                out.write(buffer, 0, len);
            }
            System.out.println("filepath:" + proFile.getFile());

        } catch (FileNotFoundException ex) {
            Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            //关闭文件输入流
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //关闭输出流
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    /**
     * 上传文件的处理
     *
     * @param proID
     * @param multipartFile
     */
    public void addProFile(int proID, MultipartFile multipartFile, String contextPath, String userName) {
        ProFile proFile = new ProFile();

        //上面建立project要改为从数据库中读取id为proID的project
        proFile.setProject(managerDao.loadProjectById(proID));

        proFile.setName(multipartFile.getOriginalFilename());

        proFile.setUploadDate(new Date());

        proFile.setUserName(userName);
//        String fileName = UUID.randomUUID().toString() + "_" + multipartFile.getOriginalFilename();
//        //创建保存文件的目录：主目录+LabRegistration+proFile+项目名
//        String savePath = contextPath + "/WEBINF/ProFile/" + project.getName() + '/' + multipartFile.getOriginalFilename();
//        //同时在proFile中记录文件的位置以便写入数据库保存
//        proFile.setFile(savePath);
        proFile.setName(multipartFile.getOriginalFilename());
        managerDao.addProFile(multipartFile, proFile, contextPath);
    }

    public List<Project> listProject() {
        return managerDao.listProject();
    }

    public List<ProFile> listProFile(String proName) {
        return managerDao.listProFile(proName);
    }

    /**
     * 添加物品
     *
     * @param g
     */
    public void addGoods(Goods g) {
        goodsDao.addGoods(g);
    }

    /**
     * 更新物品
     *
     * @param g
     */
    public void updateGoods(Goods g) {
        goodsDao.upDate(g);
    }

    /**
     * 删除物品
     *
     * @param g
     */
    public void deleteGoods(Goods g) {
        goodsDao.delete(g);
    }

    /**
     * 列出物品
     *
     * @param key
     * @return
     */
    public List<UserGoodsDTO> listGoods(String key) {
        return goodsDao.listUserGoodsDTO(key);
    }

    public Goods loadGoodsById(int gid) {
        return goodsDao.loadGoodsById(gid);
    }

    public Borrow loadBorrowById(int bid) {
        return goodsDao.loadBorrowByid(bid);
    }

    /**
     * 添加
     *
     * @param act
     */
    public void addActivity(Activity act) {
        managerDao.addActivity(act);
    }

    /**
     * 更新活动
     *
     * @param act
     */
    public void updateActivity(Activity act) {
        managerDao.updateActivity(act);
    }

    /**
     * 删除活动
     *
     * @param act
     */
    public void deleteActivity(Activity act) {
        managerDao.deleteActivity(act);
    }

    /**
     * 列出带有关键字的活动
     *
     * @param key
     * @return
     */
    public List<Activity> listActivity(String key) {
        return managerDao.listActivity(key);
    }

    public Activity getActivityById(int aid) {
        return managerDao.loadActivityById(aid);
    }

    /**
     * ccp 加载用户信息
     *
     * @param userId
     * @return
     */
    public User loadUser(int userId) {
        return managerDao.loadUser(userId);
    }

    /**
     * 修改用户信息 ccp
     *
     * @param user
     * @return
     */
    public void updateInfo(User user) {
        managerDao.updateInfo(user);
    }

    /**
     * ccp 删除用户
     *
     * @param userId
     */
    public void deleteUser(int userId) {
        managerDao.deleteUser(userId);
    }
}
